//
//  DeviceListVC.m
//  FishTank
//
//  Created by Scott Zhu on 14/11/24.
//  Copyright (c) 2014年 Scott Zhu. All rights reserved.
//

#import "DeviceListVC.h"


#import "AddEquipVC.h"//手动添加设备

#import "AkeyConfigurationVC.h"//一键配置

#import "DeviceStateView.h"
#import "CallPoliceSettingVC.h"


@interface DeviceListVC (){
    UIView *_header;
}

@property DeviceInfo * currentDeviceInfo;
@property int  failCnt;
@property int lastSessionID;

@end

@implementation DeviceListVC

@synthesize tableView = _tableView;

-(void)failedPlus{
    self.failCnt ++;
}

-(void) failedClear{
    self.failCnt = 0;
}

-(BOOL) isFaildMax{
    [self failedPlus];
    if(self.failCnt > 3){
        [self failedClear];
        return YES;
    }
    return NO;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    [_tableView setDataSource:self];
    [_tableView setDelegate:self];
    [self _initHeaderView];
    
     [self failedClear];
//    [[NSNotificationCenter defaultCenter]
//     addObserver:self
//     selector:@selector(applicationWillResign)
//     name:UIApplicationWillResignActiveNotification
//     object:nil];
    
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc]
                                                      initWithTarget:self
                                                      action:@selector(tableViewLongPressed:)];
    [longPressGesture setMinimumPressDuration:1.5];
    [_tableView addGestureRecognizer:longPressGesture];
    
    
}




- (void)_initHeaderView{
    _header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    _header.backgroundColor = rgba(201, 202, 203, 1);
    [self.view addSubview:_header];
    UILabel *lable = [[UILabel alloc] init];
    [_header addSubview:lable];
    lable.text = @"已添加设备";
    [lable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_header).offset(20);
        make.top.equalTo(_header).offset(0);
        make.bottom.equalTo(_header).offset(0);
        make.width.equalTo(@200);
    }];
    

    _header.hidden = YES;
    _tableView.hidden = YES;
    
    
//    UIButton * button  = [UIButton buttonWithType:UIButtonTypeCustom];
//    [_header addSubview:button];
//    [button mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.equalTo(_header).offset(-20);
//        make.top.equalTo(_header).offset(5);
//        make.bottom.equalTo(_header).offset(-5);
//        make.width.equalTo(@100);
//    }];
//    
//    [button setTitle:@"测试" forState:UIControlStateNormal];
//    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
}

- (void)buttonAction:(UIButton *)button{
    
    CallPoliceSettingVC *vc = [[CallPoliceSettingVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    
}


//- (void) applicationWillResign
//{
//    NSLog(@"About to lose focus");
//    [self.navigationController popToRootViewControllerAnimated:YES];
//}

- (void) viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    NSLog(@"设备列表出现");
    //进入该页面 ，则关闭 PPPP 连接
    [SVProgressHUD dismiss];
    
    [self closeDevice];
    
    
    self.tableView.hidden = YES;
    //设置导航栏标题颜色
    NSDictionary *dic = [NSDictionary dictionaryWithObject:SS_DEVICE_BLUE_COLOR forKey:NSForegroundColorAttributeName];
    self.navigationController.navigationBar.titleTextAttributes = dic;
     //设置背景颜色
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:SS_NAVI_GRAY_COLOR] forBarMetrics:UIBarMetricsDefault];
    
    
    // 显示标签栏
    MainTabBarController *main = (MainTabBarController *)self.tabBarController;
    [main hideTabBar];
    
    [self _initData];
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
   
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    if ([SVProgressHUD isVisible]) {
         [SVProgressHUD dismiss];
    }
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


- (void)_initData{
        _deviceList  = [NSMutableArray arrayWithCapacity:1];
        NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];
        id object =  [userDefault objectForKey:SENSEN_DEVICE_AQ];
        if (object != nil &&  [object respondsToSelector:@selector(initWithCoder:)]
                && [object isKindOfClass:NSData.class]) {
            
                NSData * customData = (NSData * )object;
                NSMutableArray *  array = [NSKeyedUnarchiver unarchiveObjectWithData:customData];
                if (array.count > 0) {
                    _deviceList = array;
                    self.tableView.hidden = NO;
                    _header.hidden = YES;
                }else{
                    self.tableView.hidden = YES;
                    _header.hidden = NO;
                }
                
            }else{
                self.tableView.hidden = YES;
                _header.hidden = NO;
            }
            [_tableView reloadData];
}

//com.itboye.sunsunchina
//com.Scott.CDFishTanks
-(void)addDevice:(DeviceInfo *)deviceInfo
{
    for (DeviceInfo *tempDevice in _deviceList)
    {
        if ([deviceInfo.did isEqualToString:tempDevice.did] && [deviceInfo.password isEqualToString:tempDevice.password])
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"设备已存在，无需添加"
                                                                message:nil
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil, nil];
            [alertView show];
            return;
        }
        if ([deviceInfo.did isEqualToString:tempDevice.did])
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"设备已存在，但密码已改变，已为您修改密码"
                                                                message:nil
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil, nil];
            [alertView show];
            tempDevice.password = deviceInfo.password;
            tempDevice.macAddress = deviceInfo.macAddress;
            tempDevice.isLock = deviceInfo.isLock;
            tempDevice.ip = deviceInfo.ip;
            return;
        }
    }
    
    [self.deviceList insertObject:deviceInfo atIndex:0];
    [_tableView reloadData];
    
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    NSData * data =  [NSKeyedArchiver archivedDataWithRootObject:_deviceList];
    [userDefaults  setObject:data forKey:SENSEN_DEVICE_AQ];//存储设备列表
    [userDefaults synchronize];
}

- (BOOL)isThisDeviceExist:(DeviceInfo *)deviceInfo
{
    for (DeviceInfo *tempDevice in self.deviceList)
    {
        if ([deviceInfo.did isEqualToString:tempDevice.did])
        {
            return YES;
        }
    }
    return NO;
}





#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:SHOW_DEVICE_INFO])
    {
        DeviceControlVC *deviceControlVC = (DeviceControlVC *)[segue destinationViewController];
        [deviceControlVC setDeviceInfo:(DeviceInfo *)sender];
    }
    else if ([segue.identifier isEqualToString:SHOW_DEVICE_EDIT])
    {
        DeviceEditVC *deviceEditVC = (DeviceEditVC *)[segue destinationViewController];
        [deviceEditVC setDeviceInfo: (DeviceInfo *)sender];
    }
}

#pragma -mark- Actions
- (IBAction)moreButtonPressed:(id)sender
{
    UIActionSheet *showMore = [[UIActionSheet alloc] initWithTitle:nil delegate:self
                                                 cancelButtonTitle:@"取消"
                                            destructiveButtonTitle:@"一键配置"
                                                 otherButtonTitles:@"添加局域网设备",@"手动添加设备", nil];
    [showMore showInView:self.view];
}




- (void) tableViewLongPressed:(UILongPressGestureRecognizer *)longPressGesture
{
    
    CGPoint point = [longPressGesture locationInView:_tableView];
    
    NSIndexPath *indexPath = [_tableView indexPathForRowAtPoint: point];
    if (indexPath != nil && longPressGesture.state == UIGestureRecognizerStateBegan)
    {
        DeviceInfo *deviceInfo = (DeviceInfo *)[self.deviceList objectAtIndex: indexPath.section];
        deviceInfo.indexPath = indexPath;
        [self performSegueWithIdentifier:SHOW_DEVICE_EDIT sender:deviceInfo];
    }

}




#pragma -mark- UITableViewDataSource

// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.deviceList count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DeviceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DeviceCell_ID" forIndexPath:indexPath];
    /* 忽略点击效果 */
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    DeviceInfo *deviceInfo = [self.deviceList objectAtIndex:indexPath.section];
    //cell.contentView.width = SCREEN_WIDTH;
    [cell.deviceName setText:deviceInfo.name];
    cell.deviceUid.text = [NSString stringWithFormat:@"DID:%@", deviceInfo.did];
    cell.deviceName.textColor = [UIColor darkGrayColor];
    cell.deviceUid.textColor = [UIColor darkGrayColor];
    cell.contentView.backgroundColor = rgba(238, 239, 240, 1);
    //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    
    UIImageView * imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Disclosure Indicator"]];
    [cell addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(cell.mas_centerY);
        make.right.equalTo(cell).offset(-25);
        make.size.mas_equalTo(CGSizeMake(15, 20));
    }];
    
       return cell;
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ([[UIScreen mainScreen] bounds].size.height - 61) / (float)6;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section != self.deviceList.count - 1) {
        return 3;
    }else{
        return 0.01f;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 3)];
    footer.backgroundColor = [UIColor whiteColor];
    return footer;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 30;
    }else{
        return 0;
    }


}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    header.backgroundColor = rgba(201, 202, 203, 1);
    [self.view addSubview:header];
    UILabel *lable = [[UILabel alloc] init];
    [header addSubview:lable];
    lable.text = @"已添加设备";
    [lable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(header).offset(20);
        make.top.equalTo(header).offset(0);
        make.bottom.equalTo(header).offset(0);
        make.width.equalTo(@200);
    }];
    return header;
}






 

#pragma -mark- UITableViewDelegate
- (void)    tableView:(UITableView *)tableView
   commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
    forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        [self.deviceList removeObjectAtIndex:indexPath.section];
        
        NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
        NSData * data =  [NSKeyedArchiver archivedDataWithRootObject:_deviceList];
        [userDefaults  setObject:data forKey:SENSEN_DEVICE_AQ];//存储设备列表
        [userDefaults synchronize];
    
        [SVProgressHUD showSuccessWithStatus:@"删除成功" withDuration:1];
        [self _initData];
        
    }
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [SVProgressHUD showWithStatus:@"设备连接中..." maskType:SVProgressHUDMaskTypeBlack];
    DeviceInfo *deviceInfo = (DeviceInfo *)[self.deviceList objectAtIndex: indexPath.section];
    deviceInfo.indexPath = indexPath;
    
    NSLog(@"温度订阅 ＝%@ , 水位订阅 ＝ %@, 负载订阅 ＝ %@", deviceInfo.is_temperature_on ? @"YES" :@"NO", deviceInfo.is_level_on? @"YES" :@"NO", deviceInfo.is_load_on? @"YES" :@"NO");
    
    self.currentDeviceInfo = deviceInfo;
    [self connectDeivce];
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    dispatch_async(queue, ^{
//        
//    [[APIs sharedInstance] connectWithUid: deviceInfo.did
//                        lanSearchEnable:YES
//                        success:^(NSInteger session){
//                                          
//                            NSLog(@"Connect success with session %ld", (long)session);
//                                          
//                            dispatch_queue_t mainQueue = dispatch_get_main_queue();
//                            dispatch_async(mainQueue, ^{
//                                              
//                                NSLog(@"连接成功会话ID %ld", (long)session);
//                                [SVProgressHUD dismiss];
//                                if (deviceInfo.password.length > 0) {
//                                                  
//                                    //2. 获取数据
//                                    [self getDeviceVersion:deviceInfo];
//                                                  
//                                }else{
//                                    
//                                    //add by hebidu @20160804 ,上报日志
//                                    NSString * did = deviceInfo.did;
//                                    
//                                    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
//                                    if (deviceInfo) {
//                                        if (deviceInfo.did) {
//                                            [dictionary setObject:deviceInfo.did forKey:@"did"];
//                                        }
//                                        
//                                        if (deviceInfo.password) {
//                                            [dictionary setObject:deviceInfo.password forKey:@"password"];
//                                        }
//                                    }
//                                    
//                                    
//                                    if(did != nil){
//                                        
//                                        NSString * errMsg = [NSString stringWithFormat:@"设备密码为空,应该是被锁定了,did=%@",did];
//                                        [dictionary setObject:errMsg forKey:@"errMsg"];
//                                        [self uploadConnectFailLog:dictionary];
//                                    }else{
//                                        
//                                        NSString * errMsg  = @"设备密码为空,应该是被锁定了";
//                                        [dictionary setObject:errMsg forKey:@"errMsg"];
//                                        [self uploadConnectFailLog:dictionary];
//                                    }
//                                    
//                                                  
//                                    [[[UIAlertView alloc] initWithTitle:@"❌连接失败"
//                                                        message:@"设备DID或密码错误"
//                                                        delegate:nil
//                                                    cancelButtonTitle:@"确定"
//                                                    otherButtonTitles:nil, nil] show];
//                                    [[APIs sharedInstance] close];
//                                                  
//                                }
//                                              
//                            });
//                                     
//                                          
//         
//                        }failure:^(NSInteger errorCode) {
//                            NSString * errMsg = [self getErrMsg:errorCode];
//                            
//                            
//                            NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
//                            if (errMsg) {
//                                [dictionary setObject:errMsg forKey:@"errMsg"];
//                            }
//                            
//                            if (deviceInfo) {
//                                if (deviceInfo.did) {
//                                    [dictionary setObject:deviceInfo.did forKey:@"did"];
//                                }
//                                
//                                if (deviceInfo.password) {
//                                    [dictionary setObject:deviceInfo.password forKey:@"password"];
//                                }
//                            }
//                            
//                            //add by hebidu @20160804 ,上报日志
//                            [self uploadConnectFailLog:dictionary];
//                            
//                            
//                            dispatch_queue_t mainQueue = dispatch_get_main_queue();
//                            dispatch_async(mainQueue, ^{
//                                              
//                                NSLog(@"Connect failed with errorCode %ld", (long)errorCode);
//                                [SVProgressHUD dismiss];
//                                [[[UIAlertView alloc] initWithTitle:@"❌连接失败"
//                                                        message:[NSString stringWithFormat:@"错误信息：%@", errMsg]
//                                                        delegate:nil
//                                                        cancelButtonTitle:@"确定"
//                                                    otherButtonTitles:nil, nil] show];
//
//                            });
//                        }];
//
//        
//        
//    });//END Connect
    
}



-(void) closeDevice{
    
    [[APIs sharedInstance] close];
    [[APIs sharedInstance] close:self.lastSessionID];
}

-(void ) connectDeivce  {
    
    [self closeDevice];
    
    NSLog(@"RETRY 第%d 次连接设备",self.failCnt);
    
    DeviceListVC * that = self;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        
        [[APIs sharedInstance] connectWithUid: that.currentDeviceInfo.did
                              lanSearchEnable:YES
                                      success:^(NSInteger session){
                                          
                                          NSLog(@"Connect success with session %ld", (long)session);
                                          
                                          self.lastSessionID = (INT32) session;
                                          
                                          dispatch_queue_t mainQueue = dispatch_get_main_queue();
                                          dispatch_async(mainQueue, ^{
                                              
                                              NSLog(@"连接成功会话ID %ld", (long)session);
                                              [SVProgressHUD dismiss];
                                              if (that.currentDeviceInfo.password.length > 0) {
                                                  
                                                  //2. 获取数据
                                                  [self getDeviceVersion:that.currentDeviceInfo];
                                                  
                                              }else{
                                                  
                                                  //add by hebidu @20160804 ,上报日志
                                                  NSString * did = that.currentDeviceInfo.did;
                                                  
                                                  NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
                                                  if (that.currentDeviceInfo) {
                                                      if (that.currentDeviceInfo.did) {
                                                          [dictionary setObject:that.currentDeviceInfo.did forKey:@"did"];
                                                      }
                                                      
                                                      if (that.currentDeviceInfo.password) {
                                                          [dictionary setObject:that.currentDeviceInfo.password forKey:@"password"];
                                                      }
                                                  }
                                                  
                                                  
                                                  if(did != nil){
                                                      
                                                      NSString * errMsg = [NSString stringWithFormat:@"设备密码为空,应该是被锁定了,did=%@",did];
                                                      [dictionary setObject:errMsg forKey:@"errMsg"];
                                                      [self uploadConnectFailLog:dictionary];
                                                  }else{
                                                      
                                                      NSString * errMsg  = @"设备密码为空,应该是被锁定了";
                                                      [dictionary setObject:errMsg forKey:@"errMsg"];
                                                      [self uploadConnectFailLog:dictionary];
                                                  }
                                                  
                                                  
                                                  [[[UIAlertView alloc] initWithTitle:@"❌连接失败"
                                                                              message:@"设备DID或密码错误"
                                                                             delegate:nil
                                                                    cancelButtonTitle:@"确定"
                                                                    otherButtonTitles:nil, nil] show];
                                                  [[APIs sharedInstance] close];
                                                  
                                              }
                                              
                                          });
                                          
                                          
                                          
                                      }failure:^(NSInteger errorCode) {
                                          
                                          //重连
                                          if(![that isFaildMax]){
                                              [self connectDeivce];
                                              return ;
                                          }
                                          
                                          NSString * errMsg = [self getErrMsg:errorCode];
                                          
                                          
                                          NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
                                          if (errMsg) {
                                              [dictionary setObject:errMsg forKey:@"errMsg"];
                                          }
                                          
                                          if (that.currentDeviceInfo) {
                                              if (that.currentDeviceInfo.did) {
                                                  [dictionary setObject:that.currentDeviceInfo.did forKey:@"did"];
                                              }
                                              
                                              if (that.currentDeviceInfo.password) {
                                                  [dictionary setObject:that.currentDeviceInfo.password forKey:@"password"];
                                              }
                                          }
                                          
                                          //add by hebidu @20160804 ,上报日志
                                          [self uploadConnectFailLog:dictionary];
                                          
                                          
                                          dispatch_queue_t mainQueue = dispatch_get_main_queue();
                                          dispatch_async(mainQueue, ^{
                                              
                                              NSLog(@"Connect failed with errorCode %ld", (long)errorCode);
                                              [SVProgressHUD dismiss];
                                              
                                              [[[UIAlertView alloc] initWithTitle:@"请重试"
                                                                          message:[NSString stringWithFormat:@"网络不稳定或设备不在线"]
                                                                         delegate:nil
                                                                cancelButtonTitle:@"我知道了"
                                                                otherButtonTitles:nil, nil] show];
                                              
                                          });
                                      }];
        
        
        
    });//END Connect
    
    
}



-(void) getDeviceVersion:(DeviceInfo *) info{
    __block DeviceListVC * that = self;
    [SVProgressHUD showWithStatus:@"正在获取设备信息..." maskType:SVProgressHUDMaskTypeBlack];
    UINT32 timeout = 10000; //10秒超时
    NSLog(@"%@", info.password);
    [[APIs sharedInstance] getDeviceVersionWithpassword:info.password timeout:timeout success:^(DeviceMainVersion version,NSString * majorVersion,NSString * minVersion){
        
        NSLog(@"设备信息获取成功 %hhu,%@",version,majorVersion);
        
        DeviceSun * device = [DeviceSun defaultDevice];
        
        device.versionInfo = [NSString stringWithFormat:@"版本信息=%@,次=%@",majorVersion,minVersion];
        device.version = version;
        
        if(version == AQ805){
            //如果是AQ805 ，则需要订阅令牌
            [self getSubscribeToken:info];
        }else{
            [self syncTimeToDevice:info];
        }
    } interupted:^(NSInteger errCode){
        
        //重连
        if(![that isFaildMax]){
            [self connectDeivce];
            return ;
        }

        
        //add by hebidu @20160804 ,上报日志
        NSString * errMsg = [NSString stringWithFormat:@"获取设备信息失败"];
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        if (errMsg) {
            [dictionary setObject:errMsg forKey:@"errMsg"];
        }
        
        if (info) {
            if (info.did) {
                [dictionary setObject:info.did forKey:@"did"];
            }
            
            if (info.password) {
                [dictionary setObject:info.password forKey:@"password"];
            }
        }
        
        [self uploadConnectFailLog:dictionary];
        [[APIs sharedInstance] close];
        [SVProgressHUD showErrorWithStatus:@"获取设备信息失败"];

    }];
    
}

-(void) getSubscribeToken:(DeviceInfo *) info{
    
    
    
    
    [SVProgressHUD showWithStatus:@"正在订阅设备令牌..." maskType:SVProgressHUDMaskTypeBlack];
    [DeviceControlVC updateSubscribeToken:info success:^(NSNumber *loadSubID ,NSNumber *  levelSubID ,NSNumber * tempSubID){
        
        [self syncTimeToDevice:info];
        
    } interupted:^(NSInteger errCode){
        
        //订阅令牌获取失败后关闭推送按钮
        [info setIs_level_on:NO];
        [info setIs_load_on:NO];
        [info setIs_temperature_on:NO];

        
        DeviceInfo *deviceInfo = [self.deviceList objectAtIndex:info.indexPath.section];
        [deviceInfo setIs_level_on:NO];
        [deviceInfo setIs_load_on:NO];
        [deviceInfo setIs_temperature_on:NO];
        
        [self.deviceList replaceObjectAtIndex:info.indexPath.section withObject:deviceInfo];
        [self.tableView reloadData];
        
        NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
        NSData * data =  [NSKeyedArchiver archivedDataWithRootObject:self.deviceList];
        [userDefaults  setObject:data forKey:SENSEN_DEVICE_AQ];//存储设备列表
        [userDefaults synchronize];

        
        
        NSString * errMsg = [NSString stringWithFormat:@"订阅设备令牌失败"];
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        if (errMsg) {
            [dictionary setObject:errMsg forKey:@"errMsg"];
        }
        
        if (info) {
            if (info.did) {
                [dictionary setObject:info.did forKey:@"did"];
            }
            
            if (info.password) {
                [dictionary setObject:info.password forKey:@"password"];
            }
        }
        
        //add by hebidu @20160804 ,上报日志
        [self uploadConnectFailLog:dictionary];
        [[APIs sharedInstance] close];
        [SVProgressHUD showErrorWithStatus:@"订阅设备令牌失败"];
        
    }];
    
}

//同步时间
-(void) syncTimeToDevice:(DeviceInfo *) info{
    
    [SVProgressHUD showWithStatus:@"正在同步设备时间..." maskType:SVProgressHUDMaskTypeBlack];
    
    [[APIs sharedInstance] syncTimeToDevice:info.password success:^( ){
        
        NSLog(@"同步设备时间");
        [self performSegueWithIdentifier:SHOW_DEVICE_INFO sender:info];
        
    } interupted:^(NSInteger errCode){
        NSString * errMsg = [NSString stringWithFormat:@"同步设备时间失败(%@)",[DeviceCtrl getPPPPWriteMsg:(int)errCode]];
        
        //add by hebidu @20160804 ,上报日志
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        if (errMsg) {
            [dictionary setObject:errMsg forKey:@"errMsg"];
        }
        
        if (info) {
            if (info.did) {
                [dictionary setObject:info.did forKey:@"did"];
            }
            
            if (info.password) {
                [dictionary setObject:info.password forKey:@"password"];
            }
        }
        
        [self uploadConnectFailLog:dictionary];
        
        [[APIs sharedInstance] close];
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"同步设备时间失败(%@)",[DeviceCtrl getPPPPWriteMsg:(int)errCode]]];
        
    }];
}

-(void) uploadConnectFailLog:(NSMutableDictionary *)dictionary{
    [ByLogCollector uploadSmartConfigLog:dictionary];
}



-(NSString *) getErrMsg:(int) errCode{
    return [DeviceCtrl getPPPPConnectErrMsg:errCode];
}

#pragma -mark- UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        //[self performSegueWithIdentifier:SHOW_SMART_CONFIG sender:self];
        AkeyConfigurationVC *vc = [[AkeyConfigurationVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (1 == buttonIndex)
    {
        [self performSegueWithIdentifier:SHOW_ADD_DEVICE sender:self];
    }
    
    else if (2 == buttonIndex){
        AddEquipVC *vc = [[AddEquipVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
//    else if(3 == buttonIndex){
//        FixDeviceVC * vc = [[FixDeviceVC alloc] init];
//        [self.navigationController pushViewController:vc animated:YES];
//    }
}


#pragma mark 分割线距离左边距离
-(void)viewDidLayoutSubviews
{
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}


@end
